<template>
  <div class="register-container min-h-screen p-20px">
    <div class="content-wrapper m-auto flex items-center justify-between w-full max-w-1200px min-h-80vh rounded-12px overflow-hidden">
      <div class="header-section flex-1 flex flex-col justify-center items-center p-40px text-center md:p-30px 20px">
        <div class="header text-white font-bold text-[50px] mb-20px md:text-[36px]">广西工业产品信息对接平台</div>
        <div class="sub-header text-white font-bold text-[30px] md:text-[32px]">统一身份认证平台</div>
      </div>

      <div class="form-section flex-1 flex items-center justify-center p-40px md:p-20px">
        <div class="register-form w-full max-w-400px bg-[rgba(5,31,84,0.9)] rounded-8px p-30px md:max-w-full md:p-20px">
          <div class="welcome-text text-white text-center text-18px mb-30px md:text-16px">您好，欢迎注册!</div>

          <el-form
            ref="registerForm"
            :model="form"
            :rules="rules"
            label-width="0px"
            class="register-form-content w-full"
          >
            <el-form-item
              prop="mobile"
              class="mb-25px md:mb-20px"
            >
              <el-input
                placeholder="请输入手机号"
                v-model="form.mobile"
                autocomplete="off"
              ></el-input>
            </el-form-item>

            <el-form-item
              prop="code"
              class="mb-25px md:mb-20px"
            >
              <el-input
                v-model="form.code"
                placeholder="请输入图形验证码"
                auto-complete="off"
              >
                <template #append>
                  <img
                    @click="getCaptcha"
                    class="captcha-image cursor-pointer h-38px w-100px object-cover rounded-4px"
                    :src="captchaObj?.img"
                  />
                </template>
              </el-input>
            </el-form-item>

            <el-form-item
              prop="smsCode"
              class="mb-25px md:mb-20px"
            >
              <el-input
                v-model="form.smsCode"
                placeholder="请输入手机验证码"
                auto-complete="off"
              >
                <template #append>
                  <el-button
                    :disabled="countdown > 0"
                    @click="checkPhoneBeforeGetCode"
                    class="sms-button bg-[rgb(89,109,244)] border-[rgb(89,109,244)] text-white whitespace-nowrap"
                  >
                    {{ countdown > 0 ? `${countdown}秒` : '获取验证码' }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item class="mb-25px md:mb-20px">
              <el-button
                type="primary"
                :loading="loginLoading"
                class="register-button w-full bg-[rgb(89,109,244)] border-[rgb(89,109,244)] h-40px text-16px"
                @click="submitForm"
              >
                立即注册
              </el-button>
            </el-form-item>

            <p class="login-link text-center text-white mt-20px text-14px md:text-16px">
              已有账号？<a
                @click="goToLogin"
                class="text-[#add8e6] cursor-pointer no-underline hover:text-[#409EFF]"
              >立即登录</a>
            </p>
          </el-form>
        </div>
      </div>
    </div>
    <div class="back-to-home">
      <el-button
        type="primary"
        @click="gotoHome"
      >返回首页</el-button>
    </div>
    <el-dialog
      title="请输入图形验证码确认"
      width="400px"
      :visible.sync="showDialog"
    >
      <el-input
        v-model="smsCode"
        placeholder="请输入图形验证码"
      >
        <template #append>
          <img
            @click="getPhoneCaptcha"
            class="captcha-image cursor-pointer h-38px w-100px object-cover rounded-4px"
            :src="phoneCaptchaObj?.img"
          />
        </template>
      </el-input>
      <span
        slot="footer"
        class="dialog-footer flex justify-end"
      >
        <el-button
          @click="showDialog = false"
          class="ml-10px"
        >取 消</el-button>
        <el-button
          type="primary"
          @click="getSmsCode"
          class="ml-10px"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 引入login 和 regisiter api接口
import { getcode, sendSmsCode } from "@/api/user";
import { setToken } from "@/utils/auth";
export default {
  name: "RegisterPage",
  data() {
    var validateMobile = (rule, value, callback) => {
      var reg = /^1[3-9]\d{9}$/;
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    return {
      captchaObj: {
        img: "",
        uuid: "",
      },
      phoneCaptchaObj: {
        img: "",
        uuid: "",
      },
      smsCode: "",
      form: {
        mobile: "",
        code: "",
        smsCode: null,
      },
      rules: {
        mobile: [{ validator: validateMobile, trigger: "blur" }],
        code: [
          { required: true, message: "请输入图形验证码", trigger: "blur" },
        ],
        smsCode: [
          { required: true, message: "请输入手机号验证码", trigger: "blur" },
        ],
      },
      showDialog: false,
      loginLoading: false,
      confirmLoading: false,
      countdown: 0,
    };
  },
  mounted() {
    this.getCaptcha();
  },
  methods: {
    checkPhoneBeforeGetCode() {
      this.$refs.registerForm.validateField("mobile", (valid) => {
        if (!valid) {
          // this.showDialog = true;
          this.getSmsCode();
        }
      });
    },
    getPhoneCaptcha() {
      getcode().then((res) => {
        this.phoneCaptchaObj.img = "data:image/png;base64," + res.img;
        this.phoneCaptchaObj.uuid = res.uuid;
      });
    },
    getSmsCode() {
      sendSmsCode({
        mobile: this.form.mobile,
        scene: 1,
        code: this.smsCode,
        uuid: this.phoneCaptchaObj.uuid,
      }).then((res) => {
        if (res.code === 200) {
          this.$message.success("验证码发送成功！");
          this.showDialog = false;
          this.countdown = 60;
          const timer = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(timer);
            }
          }, 1000);
        }
      });
    },
    getCaptcha() {
      getcode().then((res) => {
        this.captchaObj.img = "data:image/png;base64," + res.img;
        this.captchaObj.uuid = res.uuid;
      });
    },
    submitForm() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          this.form.uuid = this.captchaObj.uuid;
           this.$store
              .dispatch("user/register", this.form).then((res) => {
            if (res.code === 200) {
              setToken(res.data.access_token);
              this.$store.dispatch("user/getUserInfo").then((info) => {
                this.$router.push({
                  name: "center",
                  query: { activeMenu: "personalCenter" },
                });
              });
            } else {
              this.getCaptcha();
            }
          });
        } else {
          console.log("表单验证失败！");
        }
      });
    },
    goToLogin() {
      this.$router.push({ path: "/login" });
    },
    gotoHome() {
      this.$router.push({ path: "/" });
    },
  },
};
</script>

<style scoped>
.register-container {
  background: url("@/assets/image/login_bg.png");
  background-size: cover;
}
.back-to-home {
  position: absolute;
  bottom: 20px;
  right: 20px;
}
/* 覆盖 Element UI 样式 */
.register-container ::v-deep .el-form-item {
  margin-bottom: 25px;
}

.register-container ::v-deep .el-form-item__content {
  line-height: normal;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .content-wrapper {
    flex-direction: column;
  }
}

@media (max-width: 576px) {
  .register-container {
    padding: 10px;
  }

  .content-wrapper {
    border-radius: 8px;
  }
}
</style>